package com.qf.bank.web.service.impl;

import com.qf.bank.common.bo.CaptchaBO;
import com.qf.bank.common.utils.CaptchaUtils;
import com.qf.bank.common.utils.QiniuUtils;
import com.qf.bank.common.utils.QrCodeUtils;
import com.qf.bank.common.utils.SmsUtils;
import com.qf.bank.redis.utils.RedisUtils;
import com.qf.bank.userapi.api.UsersApi;
import com.qf.bank.userapi.po.Users;
import com.qf.bank.web.service.IToolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author UsersPo
 * @since 2019-12-04
 */
@Service
public class ToolServiceImpl implements IToolService {
    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private UsersApi usersApi;
    /**
     * 验证码
     */
    @Override
    public CaptchaBO captchaService() {
        CaptchaBO captchaBO = CaptchaUtils.getCaptcha();
        return captchaBO;
    }

    /**
     * 七牛云,上传
     */
    @Override
    public String qiniuService(String url) {
        try {
            String site = QiniuUtils.uploadToQiniu(new
                    FileInputStream(url));
//            返回图片链接地址
            return QiniuUtils.qiniuUrl + site;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 二维码
     */

    @Override
    public byte[] qrCodeService(String content) {
        byte[] qrCode = QrCodeUtils.getQrCode(content);
        return qrCode;
    }

    /**
     * 短信验证
     */
    @Override
    public Map<String,Boolean> smsService(String phone) {
        Map<String,Boolean> map=new HashMap<>();
//        先判断手机号是否存在
        List<Users> list = usersApi.getList(phone);
        System.out.println("*************");
        System.out.println(list);
        if(list!=null&&list.size()>0){
            map.put("userPhone",true);
        }else{
            map.put("userPhone",false);
        }
//        再判断短信是否发送成功
        String verifyCode = SmsUtils.sendSms(phone);
        if(verifyCode==null){
            map.put("note",false);
        }else{
            map.put("note",true);
 //        加入缓存
            redisUtils.addString("phone",verifyCode);
        }
        return map;
    }
    
    /**
     * 验证码判断
     */
    @Override
    public Boolean verification(String code) {
//        从缓存中取验证码
        String phone = (String)redisUtils.getString("phone");
//        比较验证码是否相同
        boolean result = phone.equals(code);
        return result;
    }
}
